package com.qf.controller;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
杨威
2021/10/4
20:27
*/
@WebServlet("/user")
public class UserController extends BaseController {
    UserService userService=new UserServiceImpl();
    public String checkLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username, password);
        if(user==null){
            return Constants.REDIRECT+"/login.jsp";
        }
        req.getSession().setAttribute("user",user);
        return Constants.REDIRECT+"/index.jsp";
    }
    public String logOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("user");
        return Constants.REDIRECT+"/login.jsp";
    }
    public String checkPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("password");
        User user = (User)req.getSession().getAttribute("user");
        if(!password.equals(user.getPassword())){
            return Constants.REDIRECT+"/password.jsp";
        }else{
            return Constants.FORWARD+"/user?method=changePassword";
        }
    }
    public String changePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String rePassword = req.getParameter("rePassword");
        int i = userService.updatePassword(rePassword);
        if(i>0){
            return Constants.REDIRECT+"/login.jsp";
        }else {
            return Constants.REDIRECT+"/password.jsp";
        }
    }
}
